#python3 prometheus operator告警转接企业微信机器人
from flask import Flask, request, jsonify
import requests
import json

app = Flask(__name__)

# 定义一个接收 POST 请求并转发的路由
@app.route('/forward', methods=['POST'])
def forward_request():
    # 获取原始请求的 JSON 数据
    original_data = request.json

    # 修改数据，这里只是简单地在原始数据中添加一个新的字段
    modified_data = original_data.copy()

    print(modified_data)

    status_ = modified_data['status']
    for alerts_one in modified_data['alerts']:
        severity_ = alerts_one['labels'].get("severity") or ""
        summarycn_ = alerts_one['annotations'].get("summaryCn") or "详情"
        summary_ = alerts_one['annotations'].get("summary") or ""
        # message_ = alerts_one['annotations'].get("message") or ""
        alertname_ = alerts_one['labels'].get("alertname") or ""
        startsat_ = alerts_one.get("startsAt") or ""
        description_ = alerts_one['annotations'].get("description") or ""

        # test = {'msgtype': 'template_card', 'template_card': {'card_type': 'text_notice', 'source': {'icon_url': 'http://xn.prd.sumztech.com:65179/favicon.ico', 'desc': '企业在线监测数据', 'desc_color': 0}, 'main_title': {'title': 'firing', 'desc': '未查到一天前数据'}, 'emphasis_content': {'title': '', 'desc': '告警级别'}, 'quote_area': {'type': 1, 'url': 'http://192.168.3.189:30880/', 'appid': 'APPID', 'pagepath': 'PAGEPATH', 'title': '详情', 'quote_text': '2024-10-22T09:12:20+08:00'}, 'sub_title_text': '在指定时间内无正常信息返回', 'card_action': {'type': 1, 'url': 'http://192.168.3.189:30880/', 'appid': 'APPID', 'pagepath': 'PAGEPATH'}}}


        # 构建转发的目标 URL
        target_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=e75f32e2-8c5c-4cc6-9bba-56fada61991e'  # 替换为实际的目标 URL

        if status_ == "firing":
            status_str = f"<font color=\"warning\">{alertname_} 异常，请相关同事注意</font>"
        elif status_ == "resolved":
            status_str = f"<font color=\"info\">{alertname_} 恢复</font>"
        else:
            status_str = f"<font color=\"comment\">{alertname_} 未知</font>"

        # markdown 消息模式
        temp_data = {
            "msgtype": "markdown",
            "markdown": {
                "content": f"""接口:{status_str} \n
                >检测:<font color=\"comment\">{summary_}</font>
                >时间:<font color=\"comment\">{startsat_}</font>
                >条件:<font color=\"comment\">{description_}</font>"""
            }
        }

        # # template_card 卡片模式
        # temp_data = {
        #     "msgtype":"template_card",
        #     "template_card":{
        #         "card_type":"text_notice",
        #         "source":{
        #             "icon_url":"http://xn.prd.sumztech.com:65179/favicon.ico",
        #             "desc": alertname_,
        #             "desc_color":0
        #         },
        #         "main_title":{
        #             "title": status_,
        #             "desc": summary_
        #         },
        #         "emphasis_content":{
        #             "title": severity_,
        #             "desc": "告警级别"
        #         },
        #         "quote_area":{
        #             "type":1,
        #             "url":"http://192.168.3.189:30880/",
        #             "appid":"APPID",
        #             "pagepath":"PAGEPATH",
        #             "title": summarycn_,
        #             "quote_text": startsat_
        #         },
        #         "sub_title_text": description_,
        #         "card_action":{
        #             "type":1,
        #             "url":"http://192.168.3.189:30880/",
        #             "appid":"APPID",
        #             "pagepath":"PAGEPATH"
        #         }
        #     }
        # }

        print(temp_data)
        data = json.dumps(temp_data)
        # 发起转发请求
        header = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"
            }
        response = requests.post(url=target_url, data=data, headers=header)

        print(response.json())

        # 返回转发请求的响应内容
        return jsonify(response.json())

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True, port=80)  # 设置启动端口

